package com.lanou.service.impl;

import com.alibaba.fastjson.JSON;
import com.lanou.entity.SearchItem;
import com.lanou.entity.SearchResult;
import com.lanou.service.SearchService;
import com.lanou.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by QuChao on 2018/12/1
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Value("${SEARCH_ITEM_JSON_URL}")
    private String SEARCH_ITEM_JSON_URL;

    @Override
    public Map<String, Object> search(String key, Integer page, Integer size) {
        String raw = HttpClientUtils.getRaw(SEARCH_ITEM_JSON_URL + "?keyword=" + key + "&page=" + page + "&rows=" + size);
        Map<String, Object> map = new HashMap<>();
        Map map1 = JSON.parseObject(raw, Map.class);
        List<Map<String, Object>> list = new ArrayList<>();
        Long count = 0L;
        if (map1.get("status").equals(200)) {
            SearchResult searchResult = HttpClientUtils.getObject(SEARCH_ITEM_JSON_URL + "?keyword=" + key + "&page=" + page + "&rows=" + size, SearchResult.class);
            List<SearchItem> documents = searchResult.getDocuments();
            for (SearchItem searchItem : documents) {
                Map<String, Object> map2 = new HashMap<>();
                map2.put("productId", searchItem.getId());
                map2.put("salePrice", searchItem.getPrice() * 0.01);
                map2.put("productName", searchItem.getTitle());
                map2.put("subTitle", searchItem.getSell_point());
                map2.put("productImageBig", "http:" + searchItem.getImage().split(",")[0]);
                list.add(map2);
            }
            count = searchResult.getRownums();
        }
        map.put("data", list);
        map.put("total", count);
        return map;
    }
}
